<template>
	<view class="container">
		<uni-forms ref="form" :rules="valiRules" :modelValue="formData">
			<slot name="headSolt"></slot>
			<block v-for="(item,index) in formItemList" :key="index">
				<!-- 输入框 -->
				<uni-forms-item v-if='item.type==="input"&&item.isShow' :label-width='labelWidth'
					:label-align='labelAlign' :label="item.label" :required='item.required' :name="item.key">
					<uni-easyinput :trim='trim' v-model="formData[item.key]" :disabled='item.readOnly'
						:placeholder='`请输入${item.label}`' />
				</uni-forms-item>
				<!-- 数字输入框 -->
				<uni-forms-item v-if='item.type==="numberInput"&&item.isShow' :label-width='labelWidth'
					:label-align='labelAlign' :label="item.label" :required='item.required' :name="item.key">
					<uni-easyinput :trim='trim' type="number" v-model="formData[item.key]" :disabled='item.readOnly'
						:placeholder='`请输入${item.label}`' />
				</uni-forms-item>
				<!-- 可加减数字输入框 -->
				<uni-forms-item v-if='item.type==="number"&&item.isShow' :label-width='labelWidth'
					:label-align='labelAlign' :label="item.label" :required='item.required' :name="item.key">
					<uni-number-box v-model="formData[item.key]" :disabled='item.readOnly'
						:placeholder='`请输入${item.label}`' :step='item.step' />
				</uni-forms-item>
				<!-- textarea类型输入框 -->
				<uni-forms-item v-if='item.type==="textarea"&&item.isShow' :label-width='labelWidth'
					:label-align='labelAlign' :label="item.label" :required='item.required' :name="item.key">
					<uni-easyinput :trim='trim' type="textarea" v-model="formData[item.key]" :disabled='item.readOnly'
						:placeholder='`请输入${item.label}`' />
				</uni-forms-item>
				<!-- 可查询下拉选择框 -->
				<uni-forms-item v-if='item.type==="inputSelect"&&item.isShow' :label-width='labelWidth'
					:label-align='labelAlign' :label="item.label" :required='item.required' :name="item.key">
					<inputSelect v-model="formData[item.key]" :localdata="item.items"
						@remoteSearch='remoteSearch(index,$event)' @change="selectInputChange" :disabled='item.readOnly'
						:placeholder="`请选择${item.label}`">
					</inputSelect>
				</uni-forms-item>
				<!-- 下拉选择框 -->
				<uni-forms-item v-if='item.type==="select"&&item.isShow' :label-width='labelWidth'
					:label-align='labelAlign' :label="item.label" :required='item.required' :name="item.key">
					<uni-data-select v-model="formData[item.key]" :localdata="item.items"
						@change="selectChange($event,item.key)" :placeholder="`请选择${item.label}`"></uni-data-select>
				</uni-forms-item>
				<!-- 单选框 -->
				<uni-forms-item v-if='item.type==="checkbox"&&item.isShow' :label-width='labelWidth'
					:label-align='labelAlign' :label="item.label" :required='item.required' :name="item.key">
					<uni-data-checkbox v-model="formData[item.key]" @change="checkoutChange" :disabled='item.readOnly'
						:localdata="item.items" />
				</uni-forms-item>
				<!-- 多选框 -->
				<uni-forms-item v-if='item.type==="checkboxMultiple"&&item.isShow' :label-width='labelWidth'
					:label-align='labelAlign' :label="item.label" :required='item.required' :name="item.key">
					<uni-data-checkbox v-model="formData[item.key]" @change="checkoutListChange" multiple
						:disabled='item.readOnly' :localdata="item.items" />
				</uni-forms-item>
				<!-- 时间选择器 -->
				<uni-forms-item
					v-if='(item.type==="date" || item.type==="daterange"|| item.type==="datetime"|| item.type==="datetimerange")&&item.isShow'
					:label-width='labelWidth' :label-align='labelAlign' :label="item.label" :required='item.required'
					:name="item.key">
					<uni-datetime-picker :hide-second="item.hideSecond" :return-type="item.format" :type="item.type"
						:disabled='item.readOnly' v-model="formData[item.key]" />
				</uni-forms-item>
				<slot :name="item.key"></slot>
			</block>
			<slot name="footSolt"></slot>
		</uni-forms>
		<button type="primary" @click="submit">{{buttonText}}</button>
	</view>
</template>

<script>
	import inputSelect from '@/components/input-select.vue'
	export default {
		components: {
			inputSelect
		},
		data() {
			return {
				// 表单数据
				formData: {}
			}
		},
		props: {
			// 页面传过来的表单数据
			pageFormData: {
				type: Object,
				default: function() {
					return {}
				}
			},
			// 表单元素集合
			formItemList: {
				type: Array,
				default: function() {
					return []
				}
			},
			// 表单分组
			groupList: {
				type: Array,
				default: function() {
					return [{
						groupKey: 'info',
						groupTxt: '信息',
						isShow: true
					}, ]
				}
			},
			// 按钮文字
			buttonText: {
				type: String,
				default: '提交'
			},
			// 表单label宽度
			labelWidth: {
				type: Number,
				default: 80
			},
			// 表单label对其方式，可选值left,right
			labelAlign: {
				type: String,
				default: 'left'
			},
			// 输入框是否去除首位空格
			trim: {
				type: Boolean,
				default: true
			},
		},
		mounted() {},
		computed: {
			// i18n() {
			// 	return this.$t('global')
			// },
			// 校验规则
			valiRules() {
				let rules = {}
				this.formItemList.forEach(item => {
					if (item.required) {
						if (item.type === 'numberInput' || item.type === 'number') {
							rules[item.key] = {
								rules: [{
										required: true,
										errorMessage: `${item.label}不能为空`
									},
									{
										validateFunction: function(rule, value, data, callback) {
											if (value <= 0) {
												callback('数值需大于0')
											}
											return true
										}
									}
								]
							}
						} else {
							rules[item.key] = {
								rules: [{
									required: true,
									errorMessage: item.type === 'input' || item.type === 'textarea' ||
										item.type === 'numberInput' ? `${item.label}不能为空` :
										`请选择${item.label}`
								}]
							}
						}
					}
				})
				return rules
			}
		},
		created() {
			this.initFormData()
			// this.getFormItemValue()
		},
		watch: {},
		methods: {
			// 设置对应字段下拉框数据
			setSelectItems(key, items) {
				/*
				 * key：需要设置的字段
				 * items：下拉框的数据(例：[{ text: 'text1', value: value }, { text: 'text2', value: value2 }])
				 */
				let index = this.formItemList.findIndex((e) => {
					return e.key === key
				})
				if (index > -1 && items.length > 0) {
					this.formItemList[index].items = items
				} else {
					this.formItemList[index].items = []
				}
			},
			// 初始化formData
			initFormData() {
				if (Object.keys(this.pageFormData).length === 0) {
					this.formData = this.$initFormData(this.formItemList)
				} else {
					this.formData = this.pageFormData
				}
				// console.log('==========>',this.formData)
			},
			// 多选框选项改变时候调用
			checkoutListChange(e) {
				console.log('多选', e)
			},

			// 单选框选项改变时候调用
			checkoutChange(e) {
				console.log('单选', e)
			},

			// inputSelect组件远程搜索
			remoteSearch(i, val) {
				console.log(this.formItemList)
				this.$emit('remoteSearch', i, val)
			},

			// inputSelect组件选项改变时候调用
			selectInputChange(e) {
				console.log('inputSelect', e)
			},

			// select组件选项改变时候调用
			selectChange(e, key) {
				// console.log('select', e)
				this.$emit('selectChange', e, key)
			},

			// 表单提交方法
			submit() {
				this.$refs['form'].validate().then(res => {
					// uni.showToast({
					// 	title: `校验通过`
					// })
					this.$emit('submit', this.formData)
				}).catch(err => {
					// console.log('err', err);
				})
			}
		}
	}
	/*
	** 对象为深层时候使用（不完善）
		// inputChange(e){
		// 	_.set(this.formData, item.key, item.value)
		// },
		// getFormItemValue(key) {
		// 	// let key = 'person.name'
		// 	// Split the key to access nested properties in formData
		// 	const keys = key.split('.');
		// 	let value = this.formData;
		// 	console.log(keys);
		// 	keys.forEach(k => {
		// 		console.log(k);
		// 		value = value[k];
		// 	});
		// 	console.log('value-------->', value);
		// 	return value;
		// },
	*/
</script>

<style lang="less" scoped>
	/deep/ .uni-forms-item__content {
		display: flex;
		align-items: center;
	}

	/deep/ .uni-numbox {
		height: 100%;

		.uni-numbox__value {
			box-sizing: border-box;
			width: 100% !important;
			height: 100%;
			border: 1px solid #eee;
			background-color: #fff;
		}
	}

	/deep/ .uni-forms-item {
		margin-bottom: 34rpx;
	}
</style>